/**
 * Created by linyi on 2019/3/12
 */
import React from 'react'
import PropTypes from 'prop-types'
import { Select, Spin } from 'antd'

const { Option } = Select

class SelectorWithAll extends React.Component {
  constructor(props) {
    super(props)

    this.state = {}
  }

  render() {
    const { loading, choices: passedChoices, ...passedProps } = this.props

    const choices = [{ value: 'ALL', label: '全部' }, ...passedChoices]

    return (
      <Select
        allowClear
        mode="multiple"
        notFoundContent={loading ? <Spin size="small" /> : null}
        {...passedProps}
      >
        {choices.map(({ value, label }) => (
          <Option key={value}>{label}</Option>
        ))}
      </Select>
    )
  }
}

function choicesEleValidator(propVal) {
  if (!propVal.value || !propVal.label) {
    return new Error(
      `非法的选项，请传入含有 value 和 label 的选项对象: ${JSON.stringify(
        propVal
      )}`
    )
  }
  return null
}

SelectorWithAll.propTypes = {
  loading: PropTypes.bool,
  choices: PropTypes.arrayOf(PropTypes.objectOf(choicesEleValidator)).isRequired
}

SelectorWithAll.defaultProps = {
  loading: false
}

export default SelectorWithAll
